import { Request } from '../../utils/util.js'
let request = new Request()
let app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo : null
  },

  getUserInfo (res) {
    let data = res.detail
    if(data.userInfo) { //授权
      let params = {
        encryptedData: data.encryptedData,
        iv : data.iv,
        rawData: data.rawData,
        signature: data.signature
      }

      request.post('userinfo', res => {
        if (res.success) {
          let userInfo = res.data
          userInfo  = Object.assign(app.globalData.userInfo, userInfo)
          app.globalData.userInfo = userInfo
          wx.setStorage({
            key: 'userinfo',
            data: userInfo,
          })
        }
      }, params)

      let newInfo = { nickname: data.userInfo.nickName, avatar: data.userInfo.avatarUrl, sex: data.userInfo.gender }
      if (this.data.userInfo) {
        newInfo = Object.assign(this.data.userInfo, newInfo)
      }
      app.globalData.userInfo = newInfo
      wx.setStorage({
        key: 'userinfo',
        data: newInfo,
      })
    }

    wx.navigateBack()
  },

  onLoad: function (options) {
    wx.getStorage({
      key: 'userinfo',
      success: (res) => {
        let data = res.data
        if (data) {
          this.setData({
            userInfo: data
          })
        }
      },
    })
  }
})